package nccloud.mob.riart.message.actions;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSONObject;

import nc.bs.dao.BaseDAO;
import nc.bs.framework.common.InvocationInfoProxy;
import nc.bs.framework.common.NCLocator;
import nc.bs.framework.server.ISecurityTokenCallback;
import nc.bs.logging.Log;
import nc.bs.logging.Logger;
import nc.itf.uap.pf.IPFMetaModel;
import nc.jdbc.framework.processor.ColumnProcessor;
import nc.vo.pub.BusinessException;
import nccloud.commons.collections.MapUtils;
import nccloud.framework.mob.action.itf.IMobileAction;
import nccloud.framework.mob.container.IMobRequest;
import nccloud.framework.mob.container.MobClientInfo;
import nccloud.framework.service.ServiceLocator;
import nccloud.message.itf.IApproveMessageQueryService;
import nccloud.message.itf.IMessageQueryService;
import nccloud.message.itf.INoticeMessageQueryService;
import nccloud.message.itf.IPrealertMessageQueryService;
import nccloud.message.itf.ITodoMessageQueryService;
import nccloud.utils.mobile_riart.MessageLogger;
import nccloud.utils.riart.MsgSyncUtils;

/**
 * 查询全部审批待办
 * 
 * @author liyingtj
 *
 */
public class QueryAllMsgAction implements IMobileAction {
	private BaseDAO baseDAO;
	@Override
	public Object doAction(IMobRequest paramIRequest) {
		MessageLogger.info("第三方系统开始调用NCC移动端获取message消息【nccloud.mob.riart.message.actions.QueryAllMsgAction】........");
		String jsonStr = paramIRequest.read();
		JSONObject params = JSONObject.parseObject(jsonStr);
		MessageLogger.info("第三方系统访问NCC移动端审批，请求参数为：【"+params+"】.............");
		String msgType = "" + params.get("msgType");
		if (msgType == null || msgType.length() == 0) {
			msgType = "approve";
			params.put("msgType", msgType);
		}
		if(params.get("billno") != null) {
			Object billno = null;
			try {
				String sql = "select billno from sm_msg_approve where PK_DETAIL  = '"+params.get("billno")+"'";
				billno =  getBaseDAO().executeQuery(sql, new ColumnProcessor());
				if(billno == null) {
					throw new Exception("第三方单点移动端审批,获取的单据不存在，查询的SQL【"+sql+"】！！") ;
				}
				params.put("billno", billno);
			} catch (Exception e) {
				MessageLogger.error("第三方单点登录移动端获取消息失败【获取消息单据号：QueryAllMsgAction】，失败原因:"+e.getMessage()+"】");
			}
		}
		String userId = "";
		MobClientInfo info = new MobClientInfo();
		userId = info.getUserid();
		JSONObject result = new JSONObject();
		try {
			NCLocator.getInstance().lookup(ISecurityTokenCallback.class).token("NCSystem".getBytes(),"pfxx".getBytes());
			String dataSource = MsgSyncUtils.queryGroupSysParam("BD900");
			InvocationInfoProxy.getInstance().setUserDataSource(dataSource);
			Class<IMessageQueryService> cls = this.getItfByMsgType(msgType);
			IMessageQueryService iMessageQueryService = (IMessageQueryService) ServiceLocator
					.find(cls);
			params.put("userId", userId);
			Set<String> billTypeSet = new HashSet();
			List<JSONObject> msgs = iMessageQueryService
					.queryNCMessages(params);
			MessageLogger.info("第三方获取的审批单据消息VO【"+msgs+"】");
			if (!"approve".equals(msgType)) {
				Iterator var16 = msgs.iterator();
				while (var16.hasNext()) {
					JSONObject json = (JSONObject) var16.next();
					billTypeSet.add(json.getString("billtype"));
				}
			} else {
				List<String> billtypeList = new ArrayList();
				List<String> billIdList = new ArrayList();
				if (msgs != null && msgs.size() > 0) {
					Iterator var13 = msgs.iterator();

					while (var13.hasNext()) {
						JSONObject json = (JSONObject) var13.next();
						billIdList.add(json.getString("billid"));
						billtypeList.add(json.getString("billtype"));
						billTypeSet.add(json.getString("billtype"));
					}

					iMessageQueryService.queryBillCommitUserInfo(billtypeList,
							billIdList, msgs);
				}
			}

			result.put("items", msgs);
			int count = iMessageQueryService.queryNCMessageCount(params);
			result.put("total", count);
			result.put("billTypeToModuleMap",
					this.getModuleBybillTypeSet(billTypeSet));

		} catch (BusinessException var15) {
			MessageLogger.error("第三方单点登录移动端获取消息失败，失败原因:"+var15.getMessage()+"】");
			Logger.error(var15.getMessage(), var15);
		}catch(Exception e) {
			MessageLogger.error("第三方单点登录移动端获取消息失败，失败原因:"+e.getMessage()+"】");
			Logger.error(e.getMessage(), e);
		}

		return result;
	}

	private Map<String, String> getModuleBybillTypeSet(Set<String> billTypeSet)
			throws BusinessException {
		IPFMetaModel pFMetaModelImpl = (IPFMetaModel) ServiceLocator
				.find(IPFMetaModel.class);
		Map<String, String> map = pFMetaModelImpl
				.queryModuleOfBilltypeToMap(billTypeSet);
		return (Map) (MapUtils.isEmpty(map) ? new HashMap() : map);
	}

	protected Class getItfByMsgType(String msgType) {
		byte var3 = -1;
		switch (msgType.hashCode()) {
		case -1293089639:
			if (msgType.equals("prealert")) {
				var3 = 2;
			}
			break;
		case -1039690024:
			if (msgType.equals("notice")) {
				var3 = 1;
			}
			break;
		case -793050291:
			if (msgType.equals("approve")) {
				var3 = 0;
			}
			break;
		case 3565638:
			if (msgType.equals("todo")) {
				var3 = 3;
			}
		}

		switch (var3) {
		case 0:
			return IApproveMessageQueryService.class;
		case 1:
			return INoticeMessageQueryService.class;
		case 2:
			return IPrealertMessageQueryService.class;
		case 3:
			return ITodoMessageQueryService.class;
		default:
			return IApproveMessageQueryService.class;
		}
	}

	public BaseDAO getBaseDAO() {
		if(null == baseDAO) {
			baseDAO = new BaseDAO(InvocationInfoProxy.getInstance().getUserDataSource());
		}
		return baseDAO;
	}
}
